<?php
namespace models;

class users
{
	public $checkRules = [
        'name'     => ['string', '2,10', '用户名应该在2-10个字符'],
        'realname' => ['string', '1,10', '姓名必须填写'],
        'password' => ['string', '6,20', '密码应该在6-20个字符'],

    ];

    // 新增教师账号
    public function addTeacher($data)
    {
        $checker = new \phpGrace\tools\dataChecker($data, $this->checkRules);
        if ($checker->check()) {
            $rowCount = db('users')->where('name=?', $data['name'])->count();
            if ($rowCount > 0) {
                return '用户名已存在';
            }
            $data['password'] = md5($data['password']);
            $nid              = db('users')->add($data);
            return $nid > 0 ? '新增成功！' : '出错了，新增失败!';
        } else {
            return '新增失败！ 原因：' . $checker->error;
        }
    }

    // 取所有教师
    public function getAllTeachers()
    {
        return db('users')->where('identity=?', '教师')->order('realname')->fetchAll();

    }

    // 修改教师姓名或密码
    public function edit($data)
    {
        if ($data['password'] !== '') {
            //如果要修改密码
            if ($data['password'] !== $data['password2']) {
                die('fail');  //两次密码不一致
            }
            $data['password'] = md5($data['password']);
        } else {
            //如果只修改姓名
            unset($data['password']);
        }
        unset($data['password2']);
        unset($data['token']);
        //这里可能有问题
        db('users')->where('id=?',$data['id'])->update($data);
        SS2('auth','realname',$data['realname']);//修改session
        die('ok');
    }
}